<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/8/28
 * Time: 17:39
 */

namespace App\Http\Controllers\API\ClassGroup;


use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\ClassGroup;
use App\Models\ElectiveStudent;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ClassGroupController extends Controller
{
    public function export()
    {
        $cellData = [
            ['课组', '课组号', '学号', '姓名', '班级']
        ];
        $query = DB::table('class_groups')->get();
        foreach ($query as $item) {
            $students = DB::table('student_groups')->join('class_groups', function ($join) {
                $join->on('class_groups.id', '=', 'student_groups.class_group_id');
            })->join('elective_students', function ($join) {
                $join->on('elective_students.id', '=', 'student_groups.student_id');
            })->where(['student_groups.class_group_id' => $item->id])->get();
            foreach ($students as $student) {
                $res[] = $student->class_group_name;
                $res[] = $student->class_group_number;
                $res[] = $student->student_code;
                $res[] = $student->student_name;
                $res[] = $student->class;
                $cellData[] = $res;
                unset($res);
            }
            $count = DB::table('student_groups')->where(['student_groups.class_group_id' => $item->id])->count();
            $cellData[] = ['总计', $count];
        }
        //   dd($cellData);
        Excel::create('学生成绩', function ($excel) use ($cellData) {
            $excel->sheet('result', function ($sheet) use ($cellData) {
                $sheet->rows($cellData);
            });
        })->export('xls');
    }

    public function selection()
    {
        return ClassGroup::$selection;
    }

    public function getList(Request $request)
    {
        $open_id = $request->get('open_id', '');
        try {
            $student = Student::query()->where(['wx_key' => $open_id])->first();
            if (!$student) {
                throw new \Exception('未找到该学生');
            }
            $c_student = ElectiveStudent::query()->where(['student_code' => $student->u_code])->first();
            if (!$c_student) {
                throw new \Exception('不具备选课资格');
            }
            $classes = ClassGroup::query()->where(['selection_id' => 1, 'field' => $c_student->field])->get();
            $result[0]['name']='公共基础课';
            $result[0]['data']=$this->getItems($classes);
            $classes = ClassGroup::query()->where(['selection_id' => 2])->get();
            $result[1]['name']='日语';
            $result[1]['data']=$this->getItems($classes);
            $classes = ClassGroup::query()->where(['selection_id' => 3,])->get();
            $result[2]['name']='创新创业教育';
            $result[2]['data']=$this->getItems($classes);
            return ['success' => 'true', 'data' => $result, 'message' => '课组列表'];
        } catch (\Exception $e) {
            return response(['success' => 'false', 'message' => $e->getMessage()], 406);
        }

    }

    public function getItems($classes)
    {
        $result = [];
        if($classes){
            foreach ($classes as $items) {
                $item['class'] = $items->class_group_name;
                $item['number'] = $items->class_group_number;
                $item['id'] = $items->id;
                $item['peoples'] = $items->peoples;
                $result[] = $item;
            }
        }
        return $result;
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = ClassGroup::query()
            ->where('class_group_name', 'like', '%' . $queryString . '%')
            ->paginate();
        return $models;
    }


    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new ClassGroup();
        $model->fill($request->all());
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '新增待选课组：'.$model->class_group_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Request $request)
    {
        $id = $request->get('id');
        $ClassGroup = $this->findModel($id);
        $ClassGroup->fill($request->all());
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '修改待选课组：'. $ClassGroup->class_group_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($ClassGroup->save()) {
            return $ClassGroup;
        } else {
            return response($ClassGroup->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除待选课组：'.$model->class_group_name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = ClassGroup::findOrFail($id);
        return $model;
    }
}